package com.heima.leadnews.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.leadnews.article.mapper.ApArticleConfigMapper;
import com.heima.leadnews.article.mapper.ApArticleContentMapper;
import com.heima.leadnews.article.mapper.ArticleMapper;
import com.heima.leadnews.article.service.ArticleService3;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
@Transactional
public class ArticleService3Impl implements ArticleService3 {
@Autowired
    ArticleMapper articleMapper;
@Autowired
ApArticleContentMapper apArticleContentMapper;
@Autowired
    ApArticleConfigMapper articleConfigMapper;
    @Override
    public ResponseResult<Long> saveArticle3(ArticleDto dto) {
        if (dto.getContent()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        ApArticle apArticle=null;
        //如果没有id,则表示新增
        if (dto.getId()==null){
            //1.新增ApArticle
            apArticle = new ApArticle();
            BeanUtils.copyProperties(dto, apArticle);
            articleMapper.insert(apArticle);
            //2.新增ApArticleConfig
            ApArticleConfig apArticleConfig = new ApArticleConfig(apArticle.getId());
            articleConfigMapper.insert(apArticleConfig);

            //3.新增ApArticleContent
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.insert(apArticleContent);


        }else {
            //查询文章
     apArticle = articleMapper.selectById(dto.getId());
            System.out.println("apArticle = " + apArticle);
            if (apArticle!=null){
                BeanUtils.copyProperties(dto, apArticle);
                articleMapper.updateById(apArticle);
            }

            //先查文章内容
            ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, apArticle.getId()));

            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.updateById(apArticleContent);
            //修改文章
        }

        //返回文章id
        ResponseResult responseResult = ResponseResult.okResult(apArticle == null ? "" : apArticle.getId());

        return responseResult;
    }
}
